
import Vue from 'vue'
import VueRouter from 'vue-router'

let routes = [
  {
    path: '/register',
    name: 'register',
    meta: {
      title: '注册',
    },
    component: () => import('../views/Register.vue')
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      title: '登录'
    },
    component: () => import('../views/Login.vue')
  },
  {
    path: '/',
    redirect: '/index'
  },
  {
    path: '*',
    name: 'notfound',
    component: () => import('../views/NotFound.vue')
  }
]

Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  document.title = to.meta.title
  var token = localStorage.getItem('token')
  if (to.path == '/login') {
    if (token) {
      next('/index')
    } else {
      next()
    }
  }
  else if (to.path == '/register') {
      next()
  }
  else {
    if (token) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
